package com.bestv.search.spider.util;

import com.bestv.search.spider.connection.IConnection;
import com.bestv.search.spider.connection.impl.HttpClientConnection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SpiderUtil {

    private static Log log = LogFactory.getLog(SpiderUtil.class);

    public static byte[] getBytesByURL(String url) {
        IConnection connection = new HttpClientConnection();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        InputStream is = null;
        byte data[] = null;
        try {
            connection.connect(url, SpiderConst.GET);
            is = connection.request();
            if (is != null) {
                int ch;
                while ((ch = is.read()) != -1) {
                    byteStream.write(ch);
                }
                data = byteStream.toByteArray();
            }
        } catch (Exception e) {
            log.error("Gets bytes failed from " + url);
            log.error(e);
        } finally {
            connection.release();
            try {
                if (is != null) {
                    is.close();
                }
                if (byteStream != null) {
                    byteStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    public static byte[] convertStreamToByte(InputStream stream) {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        byte data[] = null;
        try {
            if (stream != null) {
                int ch;
                while ((ch = stream.read()) != -1) {
                    byteStream.write(ch);
                }
                data = byteStream.toByteArray();
            }
        } catch (Exception e) {
            log.error("Convert stream to byte array failed.");
            log.error(e);
        } finally {
            try {
                if (byteStream != null) {
                    byteStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    public static void addTextToFile(String text, String filePath) {
        if (text != null && !text.equals(SpiderConst.EMPTY)) {
            File file = null;
            FileOutputStream outStream = null;
            OutputStreamWriter outWriter = null;
            try {
                file = new File(filePath);
                if (!file.exists()) {
                    file.createNewFile();
                }

                outStream = new FileOutputStream(file, true);
                outWriter = new OutputStreamWriter(outStream, SpiderConst.UTF_8);
                outWriter.write(text + SpiderConst.LINE_SEPARATOR);
                outWriter.flush();
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e);
            } finally {
                try {
                    if (outWriter != null) {
                        outWriter.close();
                    }

                    if (outStream != null) {
                        outStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void createFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                log.error(e);
                e.printStackTrace();
            }
        }
    }

    public static void deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 删除目录（文件夹）以及目录下的文件
     *
     * @param sPath 被删除目录的文件路径
     */
    public static void deleteDirectory(String sPath) {
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }

        File dirFile = new File(sPath);
        if (dirFile.exists() || dirFile.isDirectory()) {
            // 删除文件夹下的所有文件(包括子目录)
            File[] files = dirFile.listFiles();
            for (int i = 0; i < files.length; i++) {
                // 删除子文件
                if (files[i].isFile()) {
                    deleteFile(files[i].getAbsolutePath());

                } else {
                    // 删除子目录
                    deleteDirectory(files[i].getAbsolutePath());
                }
            }
            // 删除当前目录
            dirFile.delete();
        }
    }

    public static String[] getOver7DaysFolders(String folder) {
        File dir = new File(folder);
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                Pattern pattern = Pattern.compile(SpiderConst.DATETIME_FORMAT_REGEX);
                Matcher matcher = pattern.matcher(name);
                if (matcher.matches()) {
                    Calendar c = Calendar.getInstance();
                    c.add(Calendar.DAY_OF_YEAR, -7);
                    SimpleDateFormat format = new SimpleDateFormat(SpiderConst.DATETIME_FORMAT);
                    String dateForInt = format.format(c.getTime());
                    return dateForInt.compareTo(name) > 0 ? true : false;
                } else {
                    return false;
                }
            }
        };
        return dir.list(filter);
    }

    public String sendRequest(String url) {
        IConnection connection = new HttpClientConnection();
        StringBuffer result = new StringBuffer();
        try {
            connection.connect(url, SpiderConst.GET);
            InputStream is = connection.request();
            if (is != null) {
                BufferedReader br = new BufferedReader(new InputStreamReader(is, SpiderConst.UTF_8));
                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line);
                }
            } else {
                log.warn("Gets null message from " + url);
                return null;
            }
        } catch (Exception e) {
            log.error("Gets info failed from " + url);
            log.error(e);
            e.printStackTrace();
        } finally {
            connection.release();
        }
        return new String(result.toString().getBytes());
    }
}
